import React, { useEffect, useState } from "react";
import { Form, Button, Input, Modal, message, Tooltip, Select } from "antd";
import type { FormProps, TableProps } from "antd";
import styles from "./styles.module.less";
import Header from "./header";
import TableContent from "./table";
import { useShallow } from "zustand/react/shallow";
import { getCoordList, useMainStore } from "@/store/mainStore";
import { GetCharacterBaseAddress } from "@go/app/App";
import { StartClipboard, StopClipboard } from "@go/app/ClipboardApp";
import { EventsOn } from "@runtime";
import { randomId } from "@/utils/utils";

const Teleport = () => {
  const [loading, setLoading] = useState(false);
  const {
    isLogin,
    currentHwnd,
    initialSettingFormValues,
    currentCategory,
    categoryList,
  } = useMainStore(
    useShallow((state) => ({
      isLogin: state.isLogin,
      currentHwnd: state.currentHwnd,
      initialSettingFormValues: state.initialSettingFormValues,
      currentCategory: state.currentCategory,
      categoryList: state.categoryList,
    }))
  );

  const updateBaseAddress = async () => {
    setLoading(true);
    message.loading("正在获取基址...", 0);
    try {
      await GetCharacterBaseAddress(currentHwnd as number);
    } catch (err) {
      setTimeout(() => {
        message.error(err as string);
      }, 200);
    } finally {
      setLoading(false);
      message.destroy();
    }
  };

  useEffect(() => {
    const cancel = EventsOn("clipboard", (text: string) => {
      const reg =
        /\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)(?:,(-?\d+(?:\.\d+)?))?\)/;
      const result = reg.exec(text);
      if (result) {
        const x = parseFloat(result[1]);
        const y = parseFloat(result[2]);
        const z =
          result[3] !== undefined
            ? parseFloat(result[3])
            : initialSettingFormValues.default_z_coord;
        Modal.confirm({
          title: "检测到剪贴板中有坐标信息",
          content: (
            <>
              <div>是否将坐标导入到列表中？</div>
              <div>{`X: ${x}, Y: ${y}, Z: ${z}`}</div>
            </>
          ),
          onOk() {
            useMainStore.setState((state) => {
              state.clipboardText = text;
              state.coordList = [
                {
                  id: randomId(),
                  x_coord: parseFloat(result[1]),
                  y_coord: parseFloat(result[2]),
                  z_coord:
                    result[3] !== undefined ? parseFloat(result[3]) : 200,
                  desc: "",
                  hotkey: "",
                },
                ...state.coordList,
              ];
            });
          },
        });
      }
    });
    StartClipboard();
    return () => {
      cancel();
      StopClipboard();
    };
  }, []);

  return (
    <div className={styles.teleportBox}>
      <div className={styles.header}>
        <Header />
        <div className={styles.updateBase}>
          <div>
            <span>查询：</span>
            <Select
              size="small"
              style={{ width: 150 }}
              fieldNames={{ label: "name", value: "id" }}
              allowClear
              value={currentCategory}
              options={categoryList}
              onChange={(value) => {
                useMainStore.setState({ currentCategory: value });
                getCoordList(value);
              }}
              placeholder="请选择分类"
            />
          </div>
          <Tooltip
            // color="red"
            placement="topRight"
            title={!currentHwnd ? "请先选择游戏窗口再使用该功能" : ""}
          >
            <Button
              size="small"
              loading={loading}
              disabled={!currentHwnd}
              iconPosition="end"
              onClick={updateBaseAddress}
            >
              更新基址
            </Button>
          </Tooltip>
        </div>
      </div>
      <TableContent />
    </div>
  );
};

export default Teleport;
